package cn.bestick.cblog.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import cn.bestick.cblog.dao.UserDao;
import cn.bestick.cblog.dmo.User;
import cn.bestick.cblog.dto.UserDto;
import cn.bestick.cblog.util.MD5Util;

public class UserDaoImpl extends BaseDao implements UserDao {
	Connection con = null;

	public UserDto login(User user) throws Exception {
		con = getCon();

		UserDto result = null;
		String sql = "select * from t_user where username=? and password=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, user.getUsername());
		pstmt.setString(2, MD5Util.EncoderPwdByMd5(user.getPassword()));
		ResultSet rs = pstmt.executeQuery();
		if (rs.next()) {
			result = new UserDto();
			result.setId(rs.getInt("userId"));
			result.setState(rs.getInt("state"));
			result.setNickname(rs.getString("nickname"));
			result.setImageName(rs.getString("imageName"));
			result.setEmail(rs.getString("email"));
			result.setWebsite(rs.getString("website"));
		}

		close(con);
		return result;
	}

	public void save(User user) throws Exception {
		con = getCon();

		String sql = "insert into t_user values(null,0,?,?,?,?,?,?)";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, user.getUsername());
		pstmt.setString(2, MD5Util.EncoderPwdByMd5(user.getPassword()));
		pstmt.setString(3, user.getNickname());
		pstmt.setString(4, user.getEmail());
		pstmt.setString(5, user.getWebsite());
		pstmt.setString(6, user.getImageName());
		pstmt.executeUpdate();

		close(con);
	}

	public void update(User user) throws Exception {
		con = getCon();

		String sql = "update t_user set nickname=?,imageName=?,website=? where userId=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, user.getNickname());
		pstmt.setString(2, user.getImageName());
		pstmt.setString(3, user.getWebsite());
		pstmt.setInt(4, user.getId());
		pstmt.executeUpdate();

		close(con);
	}

}
